/* eslint-disable react/display-name */
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons'
import {
  App,
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Popover,
  Row,
  Select,
  Skeleton,
} from 'antd'
import cs from 'classnames'
import Image from 'next/image'
import { forwardRef, useContext, useImperativeHandle, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import { EnumsRes } from '@/api/interface'
import { Enums } from '@/api/modules'
import { UploadFile } from '@/api/modules/entity'
import { EntityInfo, UpdateEntityInfo } from '@/api/modules/entity'
import alert from '@/assets/images/alert-circle.png'
import close from '@/assets/images/close.png'
import file from '@/assets/images/file.png'
import { GlobalContext } from '@/context'
import store from '@/store'
import { GlobalState } from '@/store'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import styles from './styles/index.module.less'

const fileTypes = [
  'image/pjpeg',
  'image/jpeg',
  'image/png',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
]

export interface EditModalRef {
  showModal: () => void
}

const EditName = forwardRef<EditModalRef, {}>((_props, ref) => {
  const t = useLocale(locale)
  const { lang } = useContext(GlobalContext)
  const { message } = App.useApp()
  const [form] = Form.useForm()

  const [isModalOpen, setIsModalOpen] = useState(false)

  useImperativeHandle(ref, () => ({ showModal }))

  const showModal = () => {
    setIsModalOpen(true)
    getEntityInfo()
    getEnums()
  }

  const { userInfo, authorities } = useSelector((state: GlobalState) => state)

  const [loading, setLoading] = useState<boolean>(true)
  const [saveLoading, setSaveLoading] = useState<boolean>(false)

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    EmirateEnums: [],
    EntityReferenceEnums: [],
  })
  const getEnums = async () => {
    const enumData = await Promise.all([
      Enums({ type: 'EmirateEnums' }),
      Enums({ type: 'EntityReferenceEnums' }),
    ])
    setEnums({
      violationTypeEnums: enumData[0].data,
      EntityReferenceEnums: enumData[1].data,
    })
  }

  const getEntityInfo = async () => {
    try {
      setLoading(true)
      const { data } = await EntityInfo({ id: userInfo.entityId })
      form.setFieldsValue({
        chairman: data.chairman,
        emirate: data.emirate?.key,
        name: data.name,
        nameAr: data.nameAr,
        reference: data.reference?.key,
        shareholdingPercentage: data.shareholdingPercentage,
      })

      setFileList(data.attachments.map((item) => item.href))
    } finally {
      setLoading(false)
    }
  }

  const [fileList, setFileList] = useState<string[]>([])

  const FileUploadComponent = () => {
    const fileInputRef = useRef<HTMLInputElement | null>(null)
    const handleFileSelect = () => {
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
        fileInputRef.current.click()
      }
    }

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files
      if (files?.length! > 5) return message.warning(t['entity.attachments.upload.length.warning'])
      if (files) {
        const uploadPromises = Array.from(files).map(async (file) => {
          const imgType = fileTypes.includes(file.type)
          const imgSize = file.size / 1024 / 1024 < 200
          if (!imgType) {
            message.warning(t['entity.attachments.upload.type.warning'])
            return null
          }
          if (!imgSize) {
            message.warning(t['entity.attachments.upload.size.warning'])
            return null
          }

          const excelFormData = new FormData()
          excelFormData.append('file', file)
          const { data } = await UploadFile(excelFormData)
          return data
        })

        const uploadedFiles = await Promise.all(uploadPromises)

        // Filter out null values (warnings) and update the state with uploaded files
        const filteredFiles = uploadedFiles.filter((file) => file !== null) as string[]

        setFileList([...fileList, ...filteredFiles])
      }
    }

    const delFile = (file: string) => {
      setFileList(fileList?.filter((item) => item !== file))
    }

    return (
      <>
        {fileList.length ? (
          <div className={styles['edit-attachments-file']}>
            {fileList.map((item) => {
              return (
                <div className={styles['edit-attachments-file-item']} key={item}>
                  <Image src={file} className={styles['file-icon']} alt="file" />
                  <span className={styles['file-text']}>{item}</span>
                  <Image
                    onClick={() => delFile(item)}
                    src={close}
                    className={styles['file-close']}
                    alt="close"
                  />
                </div>
              )
            })}
          </div>
        ) : (
          <></>
        )}

        <div className={styles['edit-attachments-add']}>
          <span onClick={handleFileSelect}>{t['entity.attachments.add']}</span>
          <input
            type="file"
            multiple
            style={{ display: 'none' }}
            ref={fileInputRef}
            onChange={handleFileUpload}
            accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
          />
        </div>
      </>
    )
  }

  const handleOk = () => {
    form.validateFields().then(async (values) => {
      try {
        setSaveLoading(true)
        await UpdateEntityInfo({
          ...values,
          id: userInfo.entityId,
          attachments: fileList.map((item) => {
            return { desc: '', href: item, id: '' }
          }),
        })

        store.dispatch({
          type: 'update-userInfo',
          payload: {
            userInfo: { ...userInfo, entityName: values.name, entityNameAr: values.nameAr },
            authorities,
          },
        })
        setIsModalOpen(false)
        message.success(t['entity.form.save.success'])
      } finally {
        setSaveLoading(false)
      }
    })
  }

  const title = (
    <>
      <div className={cs('text-[22px] font-bold Roboto pt-1 pb-7')}>{t['entity.title']}</div>
    </>
  )

  const footer = (
    <div className={cs('flex justify-end')}>
      <Button loading={saveLoading} type="primary" className={cs(styles['add'])} onClick={handleOk}>
        <span className="Roboto text-[14px] font-bold">{t['entity.save']}</span>
      </Button>
    </div>
  )

  return (
    <Modal
      centered
      title={title}
      open={isModalOpen}
      onCancel={() => setIsModalOpen(false)}
      wrapClassName={styles['edit-wrapper']}
      footer={!loading && footer}
      width="700px"
    >
      <Skeleton loading={loading} title={false} active paragraph={{ rows: 11 }}>
        <Form layout="vertical" autoComplete="off" form={form} validateTrigger="onBlur">
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.name']}
                rules={[{ required: true, message: t['entity.form.name.error'] }]}
                name="name"
              >
                <Input placeholder={t['entity.form.name']} maxLength={100} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.reference']}
                rules={[{ required: true, message: t['entity.form.reference.error'] }]}
                name="reference"
              >
                {/* <Input placeholder={t['entity.form.reference']} maxLength={100} allowClear /> */}
                <Select
                  options={enums.EntityReferenceEnums?.map((item) => ({
                    value: item?.key,
                    label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                  }))}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['entity.form.reference']}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.nameAr']}
                rules={[{ required: true, message: t['entity.form.nameAr.error'] }]}
                name="nameAr"
              >
                <Input placeholder={t['entity.form.nameAr']} maxLength={100} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.emirate']}
                rules={[{ required: true, message: t['entity.form.emirate.error'] }]}
                name="emirate"
              >
                <Select
                  options={enums.EmirateEnums?.map((item) => ({
                    value: item?.key,
                    label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                  }))}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['entity.form.emirate']}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.shareholdingPercentage']}
                rules={[{ required: true, message: t['entity.form.shareholdingPercentage.error'] }]}
                name="shareholdingPercentage"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder={t['entity.form.shareholdingPercentage']}
                  min={0}
                  max={100}
                  step={0.1}
                  precision={2}
                  controls={false}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t['entity.form.chairman']}
                rules={[{ required: true, message: t['entity.form.chairman.error'] }]}
                name="chairman"
              >
                <Input placeholder={t['entity.form.chairman']} maxLength={100} allowClear />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label={
                  <>
                    <span>{t['entity.attachments']}</span>
                    <Popover
                      placement={lang === 'en-US' ? 'right' : 'left'}
                      content={t['entity.attachments.extra']}
                    >
                      <Image
                        src={alert}
                        alt="alert"
                        className={styles['edit-attachments-alert-icon']}
                      ></Image>
                    </Popover>
                  </>
                }
                name="attachments"
              >
                <FileUploadComponent />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Skeleton>
    </Modal>
  )
})

export default EditName
